package hyl.core.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import hyl.core.Amy;
import hyl.core.MyFun;

/* 简易模式 */
public class MySqlSelect {
	// 脚本
	StringBuilder _sql = new StringBuilder();
	// 查询条件
	List<Object> _params = new ArrayList<Object>();
	// 排序
	String _orderby;
	// 分页定位
	String _page;
	MyDB db;

	public static MySqlSelect getInstance(String sql) {
		return new MySqlSelect(sql);
	}

	private MySqlSelect(String sql) {
		db = Amy.getDB1();
		iniSql(sql);
	}

	/* 添加sql */
	public void iniSql(String sql) {
		if (!MyFun.isEmpty(sql)) {
			_sql.setLength(0);
			_sql.append(sql);
		}
	}

	public void addParams(SelectWhere sw) {
		if (sw != null && !sw.isEmpty()) {
			_sql.append(SelectWhere.Kong).append(sw._where);
			_params.addAll(sw._params);
		}
	}

	/* 添加排序 */
	public void orderby(String order) {
		_orderby = order;
	}

	/* 添加分页区间 */
	public void fromto(Integer index, Integer size) {
		if (index == null || index == null) {
			_page = null;
		} else if (index == null || size != null) {
			_page = " limit " + size;
		} else {
			_page = " limit " + index + ',' + size;
		}
	}

	private String prepare() {
		if (_sql.length() == 0) {
			return null;
		}
		if (_orderby != null)
			_sql.append(_orderby);
		if (_page != null) {
			_sql.append(_page);
		}
		return _sql.toString();
	}

	/**
	 * return List<Map<String, Object>> <br>
	 * 返回对象 rs：结果集合 其他的以 countsql 字段名为键值
	 */
	public List<Map<String, Object>> getList() {
		String sql = prepare();
		if (sql == null)
			return null;
		Object[] ps1 = _params.toArray();
		List<Map<String, Object>> list = db.queryList(sql, ps1);
		return list;
	}

	/** return List<List<Object>> */
	public List<List<Object>> getList2D() {
		String sql = prepare();
		if (sql == null)
			return null;
		Object[] ps1 = _params.toArray();
		// System.out.println(JSON.toJSONString(ps1));
		List<List<Object>> result = db.queryList2D(sql, ps1);
		return result;
	}

	public Map<String, Object> getMap() {
		Object[] ps1;
		if (_sql.length() == 0) {
			return null;
		}
		ps1 = _params.toArray();
		Map<String, Object> result = db.queryMap(_sql.toString(), ps1);
		return result;
	}
}
